package com.hao.shirojwt.util.json.impl;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hao.shirojwt.util.json.JsonService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

@Slf4j
public class JacksonJsonServiceImpl implements JsonService {

    @Resource
    private ObjectMapper objectMapper;

    @Override
    public String toJSONString(Object object) {
        long beginTime = System.currentTimeMillis();
        try {
            return objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            log.error(e.getMessage(), e);
            return null;
        } finally {
            long time = System.currentTimeMillis() - beginTime;
            log.debug("JacksonJson toJSONString 序列化耗时：{}", time);
        }
    }

    @Override
    public Object parseObject(String jsonString) {
        long beginTime = System.currentTimeMillis();
        try {
            return objectMapper.readValue(jsonString, Object.class);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            return null;
        } finally {
            long time = System.currentTimeMillis() - beginTime;
            log.debug("JacksonJson parseObject 序列化耗时：{}", time);
        }
    }

    @Override
    public <T> T parseObject(String jsonString, Class<T> clazz) {
        long beginTime = System.currentTimeMillis();
        try {
            return objectMapper.readValue(jsonString, clazz);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            return null;
        } finally {
            long time = System.currentTimeMillis() - beginTime;
            log.debug("JacksonJson parseObject对象 序列化耗时：{}", time);
        }
    }

    @Override
    public <T> List<T> parseArray(String jsonString, Class<T> clazz) {
        long beginTime = System.currentTimeMillis();
        try {
            return objectMapper.readValue(jsonString, getCollectionType(List.class, clazz));
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            return null;
        } finally {
            long time = System.currentTimeMillis() - beginTime;
            log.debug("JacksonJson parseArray 序列化耗时：{}", time);
        }
    }

    /**
     * 获取泛型的Collection Type
     *
     * @param collectionClass 泛型的Collection
     * @param elementClasses  实体bean
     * @return JavaType Java类型
     */
    private JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {
        return objectMapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);
    }

}
